package top.boking.server.socket;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SocketIOEventHandler {
    
    private final SocketIOServer server;
    private final Map<String, Map<String, Object>> rooms = new ConcurrentHashMap<>();
    
    public SocketIOEventHandler(SocketIOServer server) {
        this.server = server;
    }
    
    @OnConnect
    public void onConnect(SocketIOClient client) {
        System.out.println("🔌 用户连接: " + client.getSessionId());
    }
    
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        System.out.println("用户 " + client.getSessionId() + " 断开");
        // 从所有房间中移除该用户
        rooms.values().forEach(room -> room.remove(client.getSessionId().toString()));
    }
    
    @OnEvent("join-room")
    public void onJoinRoom(SocketIOClient client, String[] roomId) {
        client.joinRoom(roomId[0]);
        System.out.println("用户 " + client.getSessionId() + " 加入展厅 " + roomId);
        
        // 初始化房间
        rooms.putIfAbsent(roomId[0], new ConcurrentHashMap<>());
        Map<String, Object> roomState = rooms.get(roomId);
        
        // 发送回调给加入的用户
        client.sendEvent("join-room", client.getSessionId().toString(), roomState);
        
        // 通知其他用户有新用户加入
        server.getRoomOperations(roomId).sendEvent("user-joined", client.getSessionId().toString());
    }
    
    @OnEvent("update-state")
    public void onUpdateState(SocketIOClient client, Object data) {

        // 获取用户所在的所有房间
        for (String roomId : client.getAllRooms()) {
            if (rooms.containsKey(roomId)) {
                rooms.get(roomId).put(client.getSessionId().toString(), data);
            }
        }
    }
    
    // 定时广播房间状态
    public void broadcastRoomStates() {
        rooms.forEach((roomId, state) -> {
            server.getRoomOperations(roomId).sendEvent("room-state", state);
        });
    }
}